package info.opensoaring.util.igc.optimize;

import info.opensoaring.api.igc.Fix;
import info.opensoaring.api.igc.FlightOptimization;
import info.opensoaring.api.igc.FlightLog;
import info.opensoaring.util.igc.LogUtil;

import java.util.ArrayList;

public class OutReturnOptimizer implements FlightOptimizer {

    private static final String description = "Out And Return";

    private static final String id = "outandreturn";

    public OutReturnOptimizer() {

    }

    @Override
    public String getDescription() {
	return description;
    }

    @Override
    public String getId() {
	return id;
    }

    public FlightOptimization optimize(FlightLog flight) {
	ArrayList<Fix> fixes = flight.getFlightFixes();

	ArrayList<Fix> optimizedFixes = new ArrayList<Fix>();

	// Calculate all possible flight legs
	int startIndex = 0;
	optimizedFixes.add(fixes.get(startIndex));
	for (int i = 0; i < 1; i++) {
	    double maxDist = 0;
	    int endIndex = startIndex + 1;
	    for (int j = endIndex; j < fixes.size(); j++) {
		double distance = LogUtil.distance(fixes.get(startIndex), fixes.get(j));
		if (distance > maxDist) {
		    maxDist = distance;
		    endIndex = j;
		}
	    }
	    optimizedFixes.add(fixes.get(endIndex));
	    startIndex = endIndex;
	}

	return new FlightOptimization(getId(), optimizedFixes.toArray(new Fix[] {}));
    }
}
